<?php

namespace platform\models\authority;

use Yii;

class Role extends \yii\base\Model
{
    public $name, $description;

    public function rules()
    {
        return [
            ['name', 'required'],
            [['name'], 'string', 'max' => 64],
            [['description'], 'string'],
        ];

    }


    public static function getRoles()
    {
        return \Yii::$app->authManager->getRoles();
    }

    public function create()
    {
        $authManager = \Yii::$app->authManager;
        $role = $authManager->createRole($this->name);
        $role->description = $this->description;
        $res = $authManager->add($role);

        if (!$res) {
            $this->addError('name', '添加角色失败');
        }

        return $this;
    }

    public function update($old_name)
    {
        $authManager = \Yii::$app->authManager;
        $role = $authManager->getRole($old_name);

        if (!$role) {
            $this->addError('name', '角色不存在');
        }

        $role->name = $this->name;
        $role->description = $this->description;

        $res = $authManager->update($old_name, $role);

        if (!$res) {
            $this->addError('name', '更新角色失败');
        }

        return $this;
    }

    public function delete($name)
    {
        $authManager = \Yii::$app->authManager;
        $role = $authManager->getRole($name);

        $res = $authManager->remove($role);

        if (!$res) {
            $this->addError('name', '删除角色失败');
        }

        return $this;
    }

    public function assign($name)
    {
        $authManager = Yii::$app->authManager;
        $routes = Yii::$app->request->post('routes');

        if (empty($routes)) {
            return;
        }

        $role = $authManager->getRole($name);

        $appRoutes = (new Route())->getAppRoutes();

        foreach ($routes as $route) {
            if (!in_array($route, $appRoutes)) {
                continue;
            }

            $permission = $authManager->getPermission($route);

            $authManager->addChild($role, $permission);
        }
    }


    public function remove($name)
    {
        $authManager = Yii::$app->authManager;
        $routes = Yii::$app->request->post('routes');

        if (empty($routes)) {
            return;
        }

        $role = $authManager->getRole($name);

        foreach ($routes as $route) {
            $permission = $authManager->getPermission($route);
            $authManager->removeChild($role, $permission);
        }
    }

    public function getAssignedPermissions($name)
    {
        $authManager = Yii::$app->authManager;
        $role = $authManager->getRole($name);
        return $authManager->getPermissionsByRole($role->name);
    }

    public static function getRole($name)
    {
        return Yii::$app->authManager->getRole($name);
    }


}